#!/usr/bin/env python
from __future__ import print_function
import os
import numpy as np
from maputility2 import maptools

def makeTempTsmap(outfile='mytsmap.fits', tsmapdir='./'):
    if len(tsmapdir) == 0:
        _tsmapdir = '.'
    elif tsmapdir.endswith('/'):
        _tsmapdir = tsmapdir[:-1]
    else:
        _tsmapdir = tsmapdir

    if not os.path.exists('%s/cmap_tpl.fits'%_tsmapdir):
        raise IOError('Do not find cmap_tpl.fits!')
    m = maptools.mapLike('%s/cmap_tpl.fits'%_tsmapdir, fill_value=np.nan)
    npix_all = m.nxpix * m.nypix
    npix_valid = 0
    for i in range(1000):
        if not os.path.exists('%s/%03i' % (_tsmapdir, i)):
            break
        filename = '%s/%03i/ts_results.dat'% (_tsmapdir, i)
        if os.path.isfile(filename):
            print('Loading %s ...' % filename)
            data = np.loadtxt(filename)
            if len(data) == 0:
                continue
            elif data.ndim == 1:
                data = np.atleast_2d(data)
            ix, iy = np.int_(data[:, 0]), np.int_(data[:, 1])
            ts = data[:, 4]
            m.map[iy, ix] = ts
            npix_valid += len(ts)
    m.saveMap(outfile)
    print('%.1f%% of the tsmap is finished!' % (float(npix_valid)/float(npix_all)*100.))

def cli():
    import argparse

    parser = argparse.ArgumentParser(description='Collect unbinned tsmap tempfile to construct a temporary tsmap!')
    parser.add_argument("-o", "-outfile", type=str, default='mytsmap.fits', help='output tsmap file')
    parser.add_argument("-dir", "-tsmapdir", type=str, default='./', help='tsmap tempfile dir')
    args = parser.parse_args()

    makeTempTsmap(args.o, args.dir)

if __name__ == '__main__': cli() 
